<script setup lang="ts">
  import { createVNode, onMounted, reactive, ref } from 'vue'
  import { message, Modal } from 'ant-design-vue'
  import { editRoleReq } from '@/api'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

  interface FormState {
    name: string
    permissions: number[]
  }

  const formState = reactive<FormState>({
    name: '',
    permissions: [],
  })

  const props = defineProps<{
    record: any
    permissionList: any[]
  }>()

  const formRef = ref()

  const showCreate = defineModel()

  const onSubmit = () => {
    formRef.value
      .validate()
      .then(async () => {
        Modal.confirm({
          title: `确认修改该角色${props.record.name}吗？`,
          icon: createVNode(ExclamationCircleOutlined),
          content: '如果确认请点击确认按钮',
          async onOk() {
            try {
              const permissions = formState.permissions.map((item) => {
                return { id: item }
              })
              const res = await editRoleReq({
                newName: formState.name,
                id: props.record.id,
                permissions,
              })
              if (res?.data) {
                message.success('角色修改成功')
                showCreate.value = false
              } else {
                message.error('角色修改失败')
              }
            } catch (error) {
              message.error('操作失败，请重试')
            }
          },
          onCancel() {},
        })
      })
      .catch(() => {})
  }

  onMounted(() => {
    formState.name = props.record.name
    formState.permissions = props.permissionList
      .filter((item: any) => {
        return props.record.permissions.includes(item.code)
      })
      .map((it) => it.id)
  })
</script>

<template>
  <a-form
    ref="formRef"
    :model="formState"
    name="EditRoleForm"
    :label-col="{ span: 4 }"
    :wrapper-col="{ span: 14 }"
    style="padding: 20px"
  >
    <a-form-item
      name="name"
      label="名称"
      :validate-trigger="['']"
      :rules="[{ required: true, message: '名称不能为空' }]"
    >
      <a-input v-model:value.trim="formState.name" />
    </a-form-item>

    <a-form-item
      name="permissions"
      label="权限"
    >
      <a-checkbox-group
        v-model:value="formState.permissions"
        :options="
          permissionList.map((item) => ({
            label: item.code,
            value: item.id,
          }))
        "
      />
    </a-form-item>

    <a-form-item :wrapper-col="{ offset: 7, span: 16 }">
      <a-button
        type="primary"
        style="width: 200px; height: 40px"
        @click="onSubmit"
        >提交
      </a-button>
    </a-form-item>
  </a-form>
</template>

<style scoped lang="less"></style>
